import React from 'react';
import {Animated, View} from 'react-native';
import PropTypes from 'prop-types';
export default class ImageSwitcher extends React.PureComponent {
  fadeInOpacity = new Animated.Value(0);

  fadeOutOpacity = new Animated.Value(1);

  state = {
    prevSource: null,
  };

  componentDidMount() {
    this.onLoad();
  }

  static propTypes = {
    containerStyle: PropTypes.object,
    source: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
    imageStyle: PropTypes.object
  };

  static defaultProps = {

  };

  componentDidUpdate() {
    this.onLoad();
  }

  componentWillReceiveProps({source: newSource}) {
    const {source} = this.props;
    if (newSource !== source) {
      this.setState({prevSource: source});
    }
  }

  onLoad = () => {
    this.fadeInOpacity.setValue(0);
    this.fadeOutOpacity.setValue(1);
    Animated.parallel([
      Animated.timing(this.fadeInOpacity, {
        toValue: 1,
        duration: 1500,
        useNativeDriver: true,
      }),
      Animated.timing(this.fadeOutOpacity, {
        toValue: 0,
        duration: 1500,
        useNativeDriver: true,
      }),
    ]).start();
  };

  render() {
    const {prevSource} = this.state;
    return (
      <View
        style={this.props.containerStyle}
      >
        <Animated.Image source={this.props.source} style={[this.props.imageStyle, {opacity: this.fadeInOpacity}]}
                        resizeMode="cover"/>
        {prevSource && (
          <Animated.Image style={[this.props.imageStyle, {opacity: this.fadeOutOpacity}]} resizeMode="cover"
                          source={prevSource}/>
        )}
      </View>
    );
  }
}
